<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:tiles="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org" lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Taxis</title>

		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta name="description" content="" />
		<meta name="author" content="" />

		<!-- basic styles -->

		<script src="../../static/jquery/jquery-2.0.3.min.js" th:src="@{/static/jquery/jquery-2.0.3.min.js}"></script>
		<link href="../../static/bootstrap/css/bootstrap.min.css" th:href="@{/static/bootstrap/css/bootstrap.min.css}" rel="stylesheet" />
		<script src="../../static/bootstrap/js/bootstrap.min.js" th:src="@{/static/bootstrap/js/bootstrap.min.js}"></script>
		<link href="../../static/font-awesome/css/font-awesome.min.css" th:href="@{/static/font-awesome/css/font-awesome.min.css}" rel="stylesheet" />			

		<link href="../../static/jquery/jquery-ui.css" th:href="@{/static/jquery/jquery-ui.css}" rel="stylesheet" />
		<script src="../../static/jquery/jquery-ui.js" th:src="@{/static/jquery/jquery-ui.js}"></script>	
	
		<!-- fonts -->

		<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300" th:href="@{'http://fonts.googleapis.com/css?family=Open+Sans:400,300'}" rel="stylesheet" />		
		
		<!-- ace styles -->

		<link href="../../static/custom/ace.min.css" th:href="@{/static/custom/ace.min.css}" rel="stylesheet" />
		<link href="../../static/custom/ace-rtl.min.css" th:href="@{/static/custom/ace-rtl.min.css}" rel="stylesheet" />
		<link href="../../static/custom/ace-skins.min.css" th:href="@{/static/custom/ace-skins.min.css}" rel="stylesheet" />

		<!--[if lte IE 8]>
		  <link href="../../static/custom/ace.min.css" th:href="@{/static/custom/ace-ie.min.css}" rel="stylesheet" />
		<![endif]-->

		<!-- inline styles related to this page -->

		<!-- ace settings handler -->

		<script src="../../static/custom/ace-extra.min.js" th:src="@{/static/custom/ace-extra.min.js}"></script>

		<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->

		<!--[if lt IE 9]>
		<script src="../../static/custom/html5shiv.js" th:src="@{/static/custom/html5shiv.js}"></script>
		<script src="../../static/custom/respond.min.js" th:src="@{/static/custom/respond.min.js}"></script>
		<![endif]-->		
	</head>

	<body tiles:fragment="content">

		<div class="breadcrumbs" id="breadcrumbs">
			<script type="text/javascript">
				try{ace.settings.check('breadcrumbs' , 'fixed')}catch(e){}
			</script>
			<ul class="breadcrumb">
				<li>
					<i class="fa fa-home home-icon"></i>								
					<a href='/' th:href="@{/}">Inicio</a>
				</li>
				<li class="active">Mantenimiento de Zonas</li>
			</ul><!-- .breadcrumb -->
		</div>			
		<div class="page-content">
			<div class="page-header">
				<h1>
					Mantenimiento de Zonas
					<small>
						<i class="fa fa-angle-double-right"></i>
						Coordenadas y pol&iacute;gonos
					</small>
				</h1>
			</div><!-- /.page-header -->
			<div class="row">
				<div class="col-xs-12">						
					<div class="col-sm-11">
						<div class="col-sm-10">
							<div id="map"></div>
						</div>
						<div class="col-sm-2">
							<form role="form">
								<div class="form-group">
									<label for="form-field-username">Nombre de la Zona</label>				
									<div class="form-group">
										<input type="text" class="form-control" role="textbox" id="campoNombre" />
										<input type="hidden" id="campoId" value=""/>
									</div>
								</div>
								<div class="form-group">
									<label for="listaZonas">Zonas</label>
									<select class="form-control" id="listaZonas" multiple="multiple" size="20">
										<option th:each="zona : ${zonas}" th:value="${zona.id}" th:text="${zona.nombre}" th:name="${zona.nombre}">Nombre de zona</option>
									</select>
								</div>
								<div class="form-group">		
									<button type="button" id="btnReset" class="btn btn-sm btn-primary">
										<i class="fa fa-refresh"></i>
										Reiniciar
									</button>
									<button type="button" id="btnGrabar" class="btn btn-sm btn-primary">
										<i class="fa fa-save"></i>
										Grabar
									</button>
								</div>
							</form>
						</div>															
					</div>						
				</div>	
			</div>					
		</div><!-- /.page-content -->
		<form style="display: hidden" th:action="@{/actualizarZona}" method="POST" id="formSubmitUpdate">
		 	  <input type="hidden" id="submitNombreUpdate" name="nombreZona" value=""/>
			  <input type="hidden" id="submitPuntosUpdate" name="puntos" value=""/>	
			  <input type="hidden" id="submitIdUpdate" name="idZona" value=""/>							  
		</form>
		<form style="display: hidden" th:action="@{/agregarZona}" method="POST" id="formSubmitNew">
		 	  <input type="hidden" id="submitNombreNew" name="nombreZona" value=""/>
			  <input type="hidden" id="submitPuntosNew" name="puntos" value=""/>							  
		</form>
		<table th:each="zona : ${zonas}" name="tablaZonas" th:id="${zona.nombre}" style="visibility: hidden;">
		  <tr th:each="punto : ${zona.puntosPoligono}"> 
		    <td th:text="${punto.latitud}"></td>
		    <td th:text="${punto.longitud}"></td>
		  </tr>
		</table>
		<table id="desc" style="visibility: hidden;">
		<tr><td id="report"></td></tr>
		</table>
		
		<style type="text/css">
		#map  {
			     	height: 800px;
			    	}
		</style>
		
		<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.2&amp;sensor=false&amp;channel=PE-MAPS&amp;language=es&amp;components=country:PE&amp;libraries=geometry"></script>
		
		<script src="../../static/maps/maplabel-compiled.js" th:src="@{/static/maps/maplabel-compiled.js}" ></script>
		
		<script th:inline="javascript">
		// <![CDATA[
var map;
var polyShape;
var markers = [];
var drag_poly = false;
var mouseDownPos;
var oldVertexPos;
var polygonArray = [];
var modoEditar = false;

$(function(){
	
	var g = google.maps;
    var a = {
        center: new g.LatLng(-12.076871051369057, -76.99525272135588),
        zoom: 13,
        mapTypeId: g.MapTypeId.ROADMAP,
        draggableCursor: 'auto',
        draggingCursor: 'move',
        disableDoubleClickZoom: true,
        zoomControlOptions: {
            style: g.ZoomControlStyle.SMALL
        }
    };
    map = new g.Map(document.getElementById("map"), a);
    setShape();
    g.event.addListener(map, "click", leftClick);

function createMarker(b, c) {
    var g = google.maps;
    var d = {
        path: 'M -1,-0.5 0,-1 1,-0.5 1,0.5 0,1 -1,0.5 z',
        strokeColor: 'red',
        strokeWeight: 1,
        fillColor: '#FFF',
        fillOpacity: 1,
        scale: 6
    };
    var f = {
        path: 'M -1,-0.5 0,-1 1,-0.5 1,0.5  0,1 -1,0.5 z',
        strokeColor: 'red',
        strokeWeight: 1,
        fillColor: '#EEE',
        fillOpacity: 0.5,
        scale: 8
    };
    var h = new g.Marker({
        position: b,
        map: map,
        icon: d,
        crossOnDrag: false,
        draggable: true
    });
    if (c) markers.splice(c, 0, h);
    else markers.push(h);
    g.event.addListener(h, "mouseover", function () {
        h.setIcon(f)
    });
    g.event.addListener(h, "mouseout", function () {
        h.setIcon(d)
    });
    g.event.addListener(h, "drag", function (e) {
        for (var m = 0, r; r = markers[m]; m++) {
            if (r == h) {
                var a = e.latLng;
                break
            }
        }
        polyShape.getPath().setAt(m, a);
        showValues()
    });
    g.event.addListener(h, "click", function () {
        for (var n = 0, s; s = markers[n]; n++) {
            if (s == h) {
                s.setMap(null);
                markers.splice(n, 1);
                break
            }
        }
        polyShape.getPath().removeAt(n);
        showValues()
    });
    return h
}

function movePoly(a) {
    if (drag_poly) {
        var b = a.latLng;
        var c = polyShape.getPath();
        for (var i = 0, n; n = oldVertexPos[i]; i++) {
            var d = n.lat() + b.lat() - mouseDownPos.lat();
            var e = n.lng() + b.lng() - mouseDownPos.lng();
            var f = new google.maps.LatLng(d, e);
            c.setAt(i, f)
        }
    }
}

function startDrag(a) {
    var g = google.maps;
    drag_poly = true;
    mouseDownPos = a.latLng;
    oldVertexPos = [];
    for (var i = 0, n; n = markers[i]; i++) {
        oldVertexPos[i] = n.getPosition();
        g.event.clearInstanceListeners(n);
        n.setMap(null)
    }
    markers.length = 0;
    map.set('draggable', false);
    g.event.addListener(map, "mousemove", movePoly);
    if (window.event) {
        window.event.returnValue = false
    }
    a.stop()
}

function mouseUp() {
    if (drag_poly) {
        drag_poly = false;
        map.set('draggable', true);
        google.maps.event.clearListeners(map, "mousemove");
        var a = polyShape.getPath();
        for (var i = 0; i < a.getLength(); i++) {
            createMarker(a.getAt(i))
        }
    }
}

function setShape() {
    var g = google.maps;
    var a = {
        strokeColor: "red",
        strokeOpacity: .8,
        strokeWeight: 3,
        fillColor: "red",
        fillOpacity: .2,
        map: map
    };
    polyShape = new g.Polygon(a);
    polyShape.listeners = [g.event.addListener(polyShape, "mousedown", startDrag), g.event.addListener(polyShape, "mousemove", movePoly)];
    document.onmouseup = mouseUp
}

function setShapeUpdate(poligono) {
    var g = google.maps;
    var a = {
        strokeColor: "red",
        strokeOpacity: .8,
        strokeWeight: 3,
        fillColor: "red",
        fillOpacity: .2,
        map: map
    };
    poligono.setOptions(a);
    poligono.listeners = [g.event.addListener(polyShape, "mousedown", startDrag), g.event.addListener(polyShape, "mousemove", movePoly)];
    document.onmouseup = mouseUp
}

function showValues() {
    var a = document.getElementById("report");
    var g = google.maps.geometry.spherical;
    var b = polyShape.getPath().getArray();
    var c = g.computeArea(b, 6371);
    if (markers.length <= 2) {
        a.innerHTML = "&nbsp;"
    } else if (markers.length > 2) {
        a.innerHTML = c.toFixed(3) + " km&sup2;"
    }
}

function getClosestLine(d) {
    var g = google.maps.geometry.spherical;
    var e = polyShape.getPath(),
        length = e.getLength(),
        list = [];
    if (length <= 2) return (length + 1);
    for (var i = 0; i < length; i++) {
        var f = e.getAt(i);
        var h = e.getAt(i + 1) || e.getAt(0);
        var a = g.computeDistanceBetween(f, h);
        var b = g.computeDistanceBetween(h, d);
        var c = g.computeDistanceBetween(f, d);
        var w = Math.sqrt(b * c * Math.pow(1 - (a / (b + c)), 2));
        list[list.length] = w
    }
    var k = 0,
        min = list[0],
        j = 0;
    while (++j < list.length) {
        if (list[j] < min) {
            min = list[j];
            k = j
        }
    }
    return (k + 1)
}

function leftClick(a) {
    if (a.latLng) {
        if (!polyShape) setShape();
        var b = getClosestLine(a.latLng);
        createMarker(a.latLng, b);
        polyShape.getPath().insertAt(b, a.latLng);
        showValues()
    }
}

function zoomToPoly() {
    if (polyShape && polyShape.getPath().getLength() > 1) {
        var b = new google.maps.LatLngBounds();
        polyShape.getPath().forEach(function (a) {
            b.extend(a)
        });
        map.fitBounds(b)
    }
}

function getData(){
	if(polyShape!=null){
		var data ="";
		var paths = polyShape.getPaths();
		//get paths
		paths.getAt(0).forEach(function(value, index){
			data+=(value.toString());
		});
		return data;
	}else {
		return null;
	}
}	
		 
		 //reset
		$('#btnReset').click(function(){
		    reset();
		});	
		 
		function reset(){
			var g = google.maps;
		    for (var i = 0, m; m = markers[i]; i++) {
		        g.event.clearInstanceListeners(m);
		        m.setMap(null)
		    }
		    if (polyShape) {
		        for (var j = 0, n; n = polyShape.listeners[j]; j++) {
		            g.event.removeListener(n)
		        }
		        polyShape.setMap(null);
		        polyShape = null
		    }
		    markers.length = 0;
		    document.getElementById("report").innerHTML = "&nbsp;";
		    if(modoEditar === true){
		    	$("#campoNombre").val('');
		    	$("#campoId").val('');
// 				$("#campoNombre").prop('readonly', false);
				modoEditar = false;
				$("#listaZonas").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected");
				$('#listaZonas').prop('disabled', false);
				redibujarPoligonos();
				
		    }		    
		}
		 
		 //grabar
		 $('#btnGrabar').click(function(){
			 var data = getData();
			 if(data){
				 if(tieneColision(polyShape)){
					 alert('La zona a generar colisiona con una zona existente');
				 } else {
					 if(modoEditar === true ){
						 var cNombre = $( '#campoNombre' ).val();
						 if(cNombre != $("#listaZonas :selected").text()){
							 var existeZona = $("#listaZonas option[name='" + cNombre + "']").length !== 0;
							 if(existeZona){
								 alert('El nombre de la zona ya existe');
								 return false;
							 }
						 }
						 $("#submitPuntosUpdate").val(data);
						 $("#submitIdUpdate").val($( "#campoId" ).val());
						 $("#submitNombreUpdate").val($( "#campoNombre" ).val());
						 $("#formSubmitUpdate").submit();
						 
					 } else {
						 var cNombre = $( '#campoNombre' ).val();
						 if(cNombre != ""){
							 var existeZona = $("#listaZonas option[name='" + cNombre + "']").length !== 0;
							 if(!existeZona){
								 $("#submitPuntosNew").val(data);
								 $("#submitNombreNew").val(cNombre);
								 $("#formSubmitNew").submit();
							 } else {
								 alert('El nombre de la zona ya existe');
							 } 
						 } else {
							 alert('El nombre de la zona no puede estar vac\u00EDo'); 
						 }		 
						 
					 }
					 
				 }				 
			 } else {
				 alert('Primero defina una zona');
			 }
		 });
		 
		 $('table[name=tablaZonas]').each(function(){
			 if($(this).find('tr')[0])
		     {
			 	 var poligono = new Array();
			     $(this).find('tr').each(function(){
			     	poligono.push(new google.maps.LatLng($(this).find("td:eq(0)").text(), $(this).find("td:eq(1)").text()));
			     });
		     
		    	 var pol = new google.maps.Polygon({
			         paths: poligono,
			         strokeColor: 'blue',
			         strokeOpacity: 0.8,
			         strokeWeight: 2,
			         fillColor: 'blue',
			         fillOpacity: 0.35
			       });
			     var latlngAux = getCenterOfPolygon(pol);
			       pol.setMap(map);
			       polygonArray.push(pol);
			       var mapLabel = new MapLabel({
			           text: $(this).attr('id'),
			           position: latlngAux,
			           map: map,
			           fontSize: 16,
			           align: 'center'
			         });
			         mapLabel.set('position', latlngAux); 
		     }
		 });
		 
		 function redibujarPoligonos(){
			 while(polygonArray[0])
			 {
				 polygonArray.pop().setMap(null);
			 }
			 polygonArray.length = 0;
			 $('table[name=tablaZonas]').each(function(){
				 if($(this).find('tr')[0])
			     {
				 	 var poligono = new Array();
				     $(this).find('tr').each(function(){
				     	poligono.push(new google.maps.LatLng($(this).find("td:eq(0)").text(), $(this).find("td:eq(1)").text()));
				     });
			     
			    	 var pol = new google.maps.Polygon({
				         paths: poligono,
				         strokeColor: 'blue',
				         strokeOpacity: 0.8,
				         strokeWeight: 2,
				         fillColor: 'blue',
				         fillOpacity: 0.35
				       });
				       pol.setMap(map);
				       polygonArray.push(pol);
			     }
			 });
		 }
		 
		 $('#listaZonas').change(function(){
			 if($("#listaZonas :selected").length == 1){
				 reset();
				 $("#campoNombre").val($("#listaZonas :selected").text());
				 $("#campoId").val($(this).val());
// 				 $("#campoNombre").prop('readonly', true);
				 modoEditar = true;
				 $('#listaZonas').prop('disabled', true);
				 polyShape = ubicarPoligono($("#listaZonas :selected").text());
				 setShapeUpdate(polyShape);
				 for(var i = 0; i < polyShape.getPath().length; i++)
	             {					 
					 createMarker(polyShape.getPath().getAt(i));
	             }
				 var index = polygonArray.indexOf(polyShape);
				 polygonArray.splice(index, 1);				 
			 }			 			    
			});
		 
		 function ubicarPoligono(nombreSelect){			 
			 var i = 0;
			 var poligono;
			 $('table[name=tablaZonas]').each(function(){
				 if($(this).find('tr')[0])
			     {
					 var nombreZona = $(this).attr('id');
				 	 if(nombreZona == nombreSelect){
				 		poligono = polygonArray[i];
				 		return false;
				 	 } else {
				 		 i++;
				 	 }
			     }
			 });
			 return poligono;
		 }
		 
		});		
		
		//detector de colisiones
		 function tieneColision(poligono)
		 {
	         for(var i = 0; i < polygonArray.length; i++)
	         {
	        	 
	     	 if(ArePolygonsOverlapped(poligono, polygonArray[i])){
	             return true;
	     	 }
	     		 
	         }
	         return false;
		 }		 
		 function ArePolygonsOverlapped(poly1, poly2)
		 {
		     if(poly1.getPath() != null && poly2.getPath() != null && poly1.getPath().length >= 3 && poly2.getPath().length >= 3)
		     {
		         //close polygons polyShape.getPath().insertAt(b, a.latLng);getAt(i)
		         poly1.getPath().insertAt(poly1.getPath().length, poly1.getPath().getAt(0)); 
		         poly2.getPath().insertAt(poly2.getPath().length, poly2.getPath().getAt(0));
		         
		         for(var i = 0; i < poly1.getPath().length-1;i++)
		         {
		             for(var k = 0; k < poly2.getPath().length-1; k++)
		             {
		     if(SimplePolylineIntersection(poly1.getPath().getAt(i),poly1.getPath().getAt(i+1),poly2.getPath().getAt(k),poly2.getPath().getAt(k+1))!=null)
		                     return true;
		             }
		         }
		         
		         return false;
		     }
		     
		     return null;
		 }		 
		 function SimplePolylineIntersection(latlong1,latlong2,latlong3,latlong4)
		 {
		     //Line segment 1 (p1, p2)
		     var A1 = latlong2.lat() - latlong1.lat();
		     var B1 = latlong1.lng() - latlong2.lng();
		     var C1 = A1*latlong1.lng() + B1*latlong1.lat();
		     
		     //Line segment 2 (p3,  p4)
		     var A2 = latlong4.lat() - latlong3.lat();
		     var B2 = latlong3.lng() - latlong4.lng();
		     var C2 = A2*latlong3.lng() + B2*latlong3.lat();

		     var determinate = A1*B2 - A2*B1;
		     var intersection;
		     if(determinate != 0)
		     {
		         var x = (B2*C1 - B1*C2)/determinate;
		         var y = (A1*C2 - A2*C1)/determinate;
		         
		         var intersect = new google.maps.LatLng(y, x)
		         
		         if(inBoundedBox(latlong1, latlong2, intersect) && 
		 inBoundedBox(latlong3, latlong4, intersect))
		             intersection = intersect;
		         else
		             intersection = null;
		     }
		     else //lines are parrallel
		         intersection = null; 
		         
		     return intersection;
		 }

		 //latlong1 and latlong2 represent two coordinates that make up the bounded box
		 //latlong3 is a point that we are checking to see is inside the box
		 function inBoundedBox(latlong1, latlong2, latlong3)
		 {
		     var betweenLats;
		     var betweenLons;
		     if(latlong1.lat() < latlong2.lat())
		         betweenLats = (latlong1.lat() <= latlong3.lat() && 
		 latlong2.lat() >= latlong3.lat());
		     else
		         betweenLats = (latlong1.lat() >= latlong3.lat() && 
		 latlong2.lat() <= latlong3.lat());
		         
		     if(latlong1.lng() < latlong2.lng())
		         betweenLons = (latlong1.lng() <= latlong3.lng() && 
		 latlong2.lng() >= latlong3.lng());
		     else
		         betweenLons = (latlong1.lng() >= latlong3.lng() && 
		 latlong2.lng() <= latlong3.lng());
		     
		     return (betweenLats && betweenLons);
		 }
		 
		 //calculo de centroide
		 function getCenterOfPolygon(polygon){
		 	var PI=22/7;
		 	var X=0;
		 	var Y=0;
		 	var Z=0;
		 	polygon.getPath().forEach(function (vertex, inex) 
		 	{
		 		lat1=vertex.lat();
		 		lon1=vertex.lng();
		 		lat1 = lat1 * PI/180;
		 		lon1 = lon1 * PI/180;
		 		X += Math.cos(lat1) * Math.cos(lon1);
		 		Y += Math.cos(lat1) * Math.sin(lon1);
		 		Z += Math.sin(lat1);
		 	});
		 	Lon = Math.atan2(Y, X);
		 	Hyp = Math.sqrt(X * X + Y * Y);
		 	Lat = Math.atan2(Z, Hyp);
		 	Lat = Lat * 180/PI;
		 	Lon = Lon * 180/PI;
		 	return new google.maps.LatLng(Lat,Lon);
		 }

		 
// 		 google.maps.event.addDomListener(window, 'load', initialize);
		 
			// ]]>
		</script>		
	</body>
</html>